package com.zuosh.netty5;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * Created by kai on 2015/12/21 0021.
 */
public class Handler2 extends ChannelHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("active2 ...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("inActive2 ...");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("2-msg" + msg.toString());
//        ByteBuf byteBuf = (ByteBuf) msg;
//        byte[] bb = new byte[byteBuf.readableBytes()];
//        byteBuf.readBytes(bb);
//        System.out.println(new String(bb));
        ctx.writeAndFlush("your msg is :" + msg);
        if (msg.equals("quit")) {
            ctx.writeAndFlush("bye-bye");
            ctx.close();
        }
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println(" channelReadComplete2 ...");
//        ByteBuf byteBuf = Unpooled.copiedBuffer("xxx2".getBytes());
//        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("heanlder2 -exception caugt... " + cause);
    }
}
